package com.codename1.samples;


import com.codename1.components.MediaPlayer;
import static com.codename1.ui.CN.*;
import com.codename1.ui.Display;
import com.codename1.ui.Form;
import com.codename1.ui.Dialog;
import com.codename1.ui.Label;
import com.codename1.ui.plaf.UIManager;
import com.codename1.ui.util.Resources;
import com.codename1.io.Log;
import com.codename1.ui.Toolbar;
import java.io.IOException;
import com.codename1.ui.layouts.BoxLayout;
import com.codename1.io.NetworkEvent;
import com.codename1.media.Media;
import com.codename1.ui.Button;
import com.codename1.ui.Image;
import com.codename1.ui.layouts.BorderLayout;
import com.codename1.io.Util;
import com.codename1.media.Media;
import com.codename1.media.MediaManager;
import com.codename1.ui.CN;
import com.codename1.ui.Component;
import com.codename1.ui.Container;
import com.codename1.ui.layouts.LayeredLayout;
import static com.codename1.ui.ComponentSelector.$;
import com.codename1.ui.animations.Motion;
import com.codename1.util.AsyncResource;
import java.util.Timer;

/**
 * This file was generated by <a href="https://www.codenameone.com/">Codename One</a> for the purpose 
 * of building native mobile applications using Java.
 */
public class VideoTransition {

    private Form current;
    private Resources theme;

    public void init(Object context) {
        // use two network threads instead of one
        updateNetworkThreadCount(2);

        theme = UIManager.initFirstTheme("/theme");

        // Enable Toolbar on all Forms by default
        Toolbar.setGlobalToolbar(true);

        // Pro only feature
        Log.bindCrashProtection(true);

        addNetworkErrorListener(err -> {
            // prevent the event from propagating
            err.consume();
            if(err.getError() != null) {
                Log.e(err.getError());
            }
            Log.sendLogAsync();
            Dialog.show("Connection Error", "There was a networking error in the connection to " + err.getConnectionRequest().getUrl(), "OK", null);
        });        
    }
    
    private Image image;
    private boolean mediaLoaded = false;
    
    public void start() {
        if(current != null){
            current.show();
            return;
        }
        Form hi = new Form("Hi World", new BorderLayout());
        Button swap = new Button("Swap");
        Container theCnt = new Container(new LayeredLayout());
        Label imageLabel = new Label();
        $(imageLabel).selectAllStyles().setBgColor(0).setBgTransparency(255);
        
        
        MediaPlayer mediaPlayer = new MediaPlayer();
        $(mediaPlayer).selectAllStyles().setBgColor(0).setBgTransparency(255);
        swap.addActionListener(e->{
            if (image == null) {
                image = Util.downloadImageToStorage("https://www.codenameone.com/img/uber-skin.png", "uber-skin.png").get();
                imageLabel.setIcon(image.scaled(CN.getDisplayWidth(), CN.getDisplayHeight()));
            }
            if (!mediaLoaded) {
                try {
                    mediaPlayer.setDataSource("https://upload.wikimedia.org/wikipedia/commons/b/b3/Big_Buck_Bunny_Trailer_400p.ogv", null);
                } catch (IOException ex) {
                    Log.e(ex);
                }
                mediaLoaded = true;
                
            }
            
            if (theCnt.getComponentCount() == 0) {
                theCnt.add(mediaPlayer);
                mediaPlayer.getMedia().play();
                hi.revalidateWithAnimationSafety();
            } else if (theCnt.contains(mediaPlayer) && !theCnt.contains(imageLabel)) {
                imageLabel.getAllStyles().setOpacity(0);
                imageLabel.getAllStyles().setBgTransparency(0);
                theCnt.add(imageLabel);
                theCnt.revalidateWithAnimationSafety();
                fadeIn(imageLabel, 500).ready(res->{
                    mediaPlayer.getMedia().pause();
                    mediaPlayer.remove();
                    hi.revalidateWithAnimationSafety();
                });
                
            } else if (theCnt.contains(imageLabel) && !theCnt.contains(mediaPlayer)) {
                theCnt.addComponent(0, mediaPlayer);
                mediaPlayer.getMedia().play();
                fadeOut(imageLabel, 500).ready(res->{
                    imageLabel.remove();
                    theCnt.revalidateWithAnimationSafety();
                });
                
            }
            
            
        });
        
        
        hi.add(BorderLayout.NORTH, swap);
        hi.add(BorderLayout.CENTER, theCnt);
        hi.show();
    }

    
    private AsyncResource<Component> fadeIn(Component cmp, int duration) {
        AsyncResource<Component> out = new AsyncResource<Component>();
        Motion m = Motion.createEaseInMotion(cmp.getStyle().getOpacity(), 255, duration);
        Timer[] ts = new Timer[1];
        Timer t = CN.setInterval(30, ()->{
            int currOpacity = cmp.getStyle().getOpacity();
            int newOpacity = m.getValue();
            if (currOpacity != newOpacity) {
                
                cmp.getStyle().setOpacity(newOpacity);
                cmp.getStyle().setBgTransparency(newOpacity);
                cmp.repaint();
            }
            if (newOpacity == m.getDestinationValue()) {
                ts[0].cancel();
                out.complete(cmp);
            }
        });
        ts[0] = t;
        m.start();
        return out;
    }
    
    private AsyncResource<Component> fadeOut(Component cmp, int duration) {
        AsyncResource<Component> out = new AsyncResource<Component>();
        Motion m = Motion.createEaseInMotion(cmp.getStyle().getOpacity(), 0, duration);
        Timer[] ts = new Timer[1];
        Timer t = CN.setInterval(30, ()->{
            int currOpacity = cmp.getStyle().getOpacity();
            int newOpacity = m.getValue();
            if (currOpacity != newOpacity) {
                cmp.getStyle().setBgTransparency(newOpacity);
                cmp.getStyle().setOpacity(newOpacity);
                cmp.repaint();
            }
            if (newOpacity == m.getDestinationValue()) {
                ts[0].cancel();
                out.complete(cmp);
            }
        });
        ts[0] = t;
        m.start();
        return out;
    }
    
    public void stop() {
        current = getCurrentForm();
        if(current instanceof Dialog) {
            ((Dialog)current).dispose();
            current = getCurrentForm();
        }
    }
    
    public void destroy() {
    }

}
